
import UIKit
 

class GradientBorderLabel: UILabel {
    
    var gradientColors: [UIColor] = [UIColor.systemBlue, UIColor.systemPink] {
        didSet { updateGradient() }
    }
    
    var borderWidth: CGFloat = 2 {
        didSet { shapeLayer.lineWidth = borderWidth; setNeedsLayout() }
    }
    
    var borderStrokeColor: UIColor = .black {
        didSet { shapeLayer.strokeColor = borderStrokeColor.cgColor }
    }
    
    private let gradientLayer = CAGradientLayer()
    private let shapeLayer = CAShapeLayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        textAlignment = .center
        layer.addSublayer(gradientLayer)
        gradientLayer.mask = shapeLayer
        clipsToBounds = false
        updateGradient()
    }
    
    private func updateGradient() {
        gradientLayer.colors = gradientColors.map { $0.cgColor }
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        setNeedsLayout()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer.frame = bounds
        
        let path = UIBezierPath(roundedRect: bounds.insetBy(dx: borderWidth / 2, dy: borderWidth / 2),
                                cornerRadius: bounds.height / 2)
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = borderStrokeColor.cgColor
        shapeLayer.lineWidth = borderWidth
    }
}
